/*
   Copyright (c) 2011, 2012 Mizar Tools Contributors (mizartools.org)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
/*  Contributors :
 *	2011-02-18 Marco Riccardi - initial implementation
 *  2012-04-06 Marco Riccardi - added message in DliParseException
 *
 */
package org.mizartools.dli;

import java.util.LinkedList;

public class Cluster {

    private LinkedList<Adjective> adjectiveList = new LinkedList<Adjective>();

	private Cluster(){}

	public Cluster(LinkedList<Adjective> adjectiveList) throws DliException {
		if (adjectiveList == null){
			throw new DliException();
		}
		this.adjectiveList = adjectiveList;
    }
    
	public static Cluster newInstance(String string) throws DliParseException {
		Cluster cluster = new Cluster();
		if (string.equals("$cluster")){
			return cluster;
		}
		int position = string.indexOf("(");
		if (position == -1) {
			throw new DliParseException("["+string+"] is not valid in Cluster");
		}
		if (!string.substring(0, position).equals("$cluster")){
			throw new DliParseException("["+string+"] is not valid in Cluster");
		}
		string = string.substring(position+1, string.length()-1);
		int positionComma = Utility.searchSeparationComma(string);
		while (positionComma != -1) {
			cluster.adjectiveList.add(Adjective.newInstance(string.substring(0, positionComma)));
			string = string.substring(positionComma+1, string.length());
			positionComma = Utility.searchSeparationComma(string);
		}
		cluster.adjectiveList.add(Adjective.newInstance(string));
		return cluster;
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("$cluster");
		if (adjectiveList.size() != 0) {
			sb.append("(");
			boolean first = true;
			for (Adjective adjective : adjectiveList){
				if (first) first = false;
				else sb.append(",");
				sb.append(adjective.toString());
			}
			sb.append(")");
		}
		return sb.toString();
	}
	
}
